package org.jash.shop2111.category

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.liveData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import org.jash.shop2111.entry.BannerEntry
import org.jash.shop2111.entry.Category
import org.jash.shop2111.entry.Goods
import org.jash.shop2111.mvvm.BaseViewModel
import org.jash.shop2111.utils.SingleLiveData
import org.jash.shop2111.utils.dao.CategoryDao
import javax.inject.Inject

@HiltViewModel
class CategoryViewModel @Inject constructor(val categoryDao: CategoryDao) : BaseViewModel() {
    val categoriesLiveData by lazy { SingleLiveData<List<Category>>() }
    fun loadCategories() {
        viewModelScope.launch {
            val categories = categoryDao.findByParentId(0)
            categories.forEach { it.data = categoryDao.findByParentId(it.id) }
            categoriesLiveData.postValue(categories)
            try {
                val res = service.getCategories()
                if (res.code == 200) {
                    categoriesLiveData.postValue(res.data)
                } else {
                    errorLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                errorLiveData.postValue(e)
            }
        }
    }
    val goodsLiveData by lazy { SingleLiveData<List<Goods>>() }
    fun loadGoods(category_id:Int, currentPage:Int, pageSize:Int) {
        val disposable =
            service.getGoodsList(category_id, currentPage, pageSize)
                .subscribe({
                    if (it.code == 200 && it.data != null) {
                        goodsLiveData.postValue(it.data)
                    } else {
                        errorLiveData.postValue(RuntimeException(it.message))
                    }
                }, errorLiveData::postValue)
        addCloseable { disposable.takeIf { !it.isDisposed }?.dispose() }

    }
    fun getPagingSource(cid:Int) = Pager(PagingConfig(pageSize = 10)) { ProductPagingSource(service, cid) }
        .flow
        .catch {
            errorLiveData.postValue(it)
        }

}